<template>
	<view class="ifun-ui ifun-date-picker">
		<ifun-tree-picker lazy :data="data" :value="displayValue" :valueFormat="handleFormatValue" v-bind="$attrs"
			@ok="handleConfirm" :load="handleLoadColumn">

		</ifun-tree-picker>
	</view>
</template>
<script>
	import {
		compareIsEqual
	} from '../utils/libs.js'
	const Type = {
		year: "年",
		'year-month': '年月',
		'month': '月',
		'date': "年月日",
		'time': "时间",
		'datetime': "时分秒",
		// "daterange": "年月日范围",
		// "timerange":"时分秒范围",
		// 'datetimerange': "年月日时分秒范围"
	}
	export default {
		name: "ifun-date-picker",
		inheritAttrs: false,
		props: {
			type: {
				type: String,
				required: true,
				validator: function(value) {

					return Object.keys(Type).includes(value)
				}
			},
			value: String,
			// 范围限定
			gap: {
				type: Array,
				default: () => []
			},
			valueFormat: Function
		},
		data() {
			return {
				currentDate: [],
				yearDate: [],
				monthData: [],
				// dayDate: [],
				data: [],
				// 时间
				hoursData: [],
				minutesData: [],
				secondsData: [],
				// 默认显示的值
				displayValue: []
			}
		},
		watch: {
			// value: {
			// 	immediate: true,
			// 	handler() {
			// 		this.handleInitValue();
			// 	}
			// },
			type: {
				immediate: true,
				handler() {

					// 当前时间
					let date = new Date();
					this.currentDate = [
						date.getFullYear(),
						date.getMonth() + 1,
						date.getDate(),
						date.getHours(),
						date.getMinutes(),
						date.getSeconds()
					];
					this.init();
					this.initPickerData();
					// 默认初始选中
					this.handleInitValue();
				}
			}
		},
		computed: {
			showYear() {
				return this.type.includes('year') || this.type.includes('date')
			},
			showMonth() {
				return this.type.includes('month') || this.type.includes('date')
			},
			showDay() {
				return this.type.includes('date')
			},
			showTime() {
				return this.type.includes('time')
			},
			// showRange() {
			// 	return this.type.includes('range')
			// }
			startYear() {

				if (this.showYear && !this.showMonth) {
					return this.gap[0] || ''
				}
				if (this.gap.length > 0 && this.showYear && this.gap[0]) {
					return this.gap[0].slice(0, 4);
				}
				return '';
			},
			endYear() {
				if (this.showYear && !this.showMonth) {
					return this.gap[1] || ''
				}
				if (this.gap.length > 1 && this.showYear && this.gap[1]) {
					return this.gap[1].slice(0, 4);
				}
				return '';
			},
			startMonth() {
				if (!this.showYear && this.showMonth) {
					return this.gap[0] || ''
				}
				if (this.gap.length > 0 && this.showMonth && this.gap[0]) {
					return this.gap[0].slice(5, 7);
				}
				return ''
			},
			endMonth() {
				if (!this.showYear && this.showMonth) {
					return this.gap[1] || ''
				}
				if (this.gap.length > 1 && this.showMonth && this.gap[1]) {
					return this.gap[1].slice(5, 7);
				}
				return ''
			},
			startDay() {
				if (!this.showDay || this.gap.length < 1 || !this.gap[0]) {
					return ''
				}
				return this.gap[0].slice(8, 10);
			},
			endDay() {
				if (!this.showDay || this.gap.length < 2 || !this.gap[1]) {
					return ''
				}
				return this.gap[1].slice(8, 10);
			},
			startHour() {

				if (!this.showTime || this.gap.length < 1 || !this.gap[0]) {
					return ''
				}
				let time = "";
				if (this.showDay) {
					time = this.gap[0].split(' ')[1] || ""
				} else {
					time = this.gap[0]
				}
				return time.slice(0, 2);
			},
			endHour() {
				if (!this.showTime || this.gap.length < 2 || !this.gap[1]) {
					return ''
				}
				let time = "";
				if (this.showDay) {
					time = this.gap[1].split(' ')[1] || ""
				} else {
					time = this.gap[1]
				}
				return time.slice(0, 2);
			},
			startSeconds() {
				if (!this.showTime || this.gap.length < 1 || !this.gap[0]) {
					return ''
				}
				let time = "";
				if (this.showDay) {
					time = this.gap[0].split(' ')[1] || ""
				} else {
					time = this.gap[0]
				}
				return time.slice(6, 8);
			},
			endSeconds() {
				if (!this.showTime || this.gap.length < 2 || !this.gap[1]) {
					return ''
				}
				let time = "";
				if (this.showDay) {
					time = this.gap[1].split(' ')[1] || ""
				} else {
					time = this.gap[1]
				}
				return time.slice(6, 8);
			},
			startMinute() {
				if (!this.showTime || this.gap.length < 1 || !this.gap[0]) {
					return ''
				}
				let time = "";
				if (this.showDay) {
					time = this.gap[0].split(' ')[1] || ""
				} else {
					time = this.gap[0]
				}
				return time.slice(3, 5);
			},
			endMinute() {
				if (!this.showTime || this.gap.length < 2 || !this.gap[1]) {
					return ''
				}
				let time = "";
				if (this.showDay) {
					time = this.gap[1].split(' ')[1] || ""
				} else {
					time = this.gap[1]
				}
				return time.slice(3, 5);
			}
		},
		mounted() {

		},
		methods: {
			/**
			 * 根据起始时间，限定小时
			 */
			formatHour(data) {
				
				let hourData = this.hoursData;
				const [year, month, day] = data.map(item => item.value);

				if (compareIsEqual([year, month, day], [this.startYear, this.startMonth, this.startDay]) && this
					.startHour) {
					hourData = hourData.filter(item => item.value * 1 >= this.startHour * 1)
				} else if (compareIsEqual([year, month, day], [this.endYear, this.endMonth, this.endDay]) && this
					.endHour) {
					hourData = hourData.filter(item => item.value * 1 <= this.endHour * 1)
				}

				return hourData;
			},
			/**
			 * 根据起始时间，限定秒数
			 */
			formatSeconds(data) {
				let secondsData = this.secondsData;

				if (!this.showDay) {
					const [hour, minute] = data.map(item => item.value);
					// time,没有日期限制
					if (compareIsEqual([hour, minute], [this.startHour, this.startMinute]) && this.startSeconds) {
						secondsData = secondsData.filter(item => item.value * 1 >= this.startSeconds * 1)
					} else if (compareIsEqual([hour, minute], [this.endHour, this.endMinute]) && this.endSeconds) {
						secondsData = secondsData.filter(item => item.value * 1 <= this.endSeconds * 1)
					}

				} else {
					const [year, month, day, hour, minute] = data.map(item => item.value);
					// datetime 有日期限制
					if (compareIsEqual([year, month, day, hour, minute], [this.startYear, this.startMonth, this.startDay,
							this.startHour, this.startMinute
						]) && this.startSeconds) {
						secondsData = secondsData.filter(item => item.value * 1 >= this.startSeconds * 1)
					} else if (compareIsEqual([year, month, day, hour, minute], [this.endYear, this.endMonth, this.endDay,
							this.endHour, this.endMinute
						]) && this.endSeconds) {
						secondsData = secondsData.filter(item => item.value * 1 <= this.endSeconds * 1)
					}
				}
				return secondsData;
			},
			/**
			 * 根据起始时间，限定分钟
			 */
			formatMinute(data) {
				let minuteData = this.minutesData;

				if (!this.showDay) {
					const [hour] = data.map(item => item.value);
					// time,没有日期限制
					if (hour == this.startHour && this.startMinute) {
						minuteData = minuteData.filter(item => item.value * 1 >= this.startMinute * 1)
					} else if (hour == this.endHour && this.endMinute) {
						minuteData = minuteData.filter(item => item.value * 1 <= this.endMinute * 1)
					}

				} else {
					const [year, month, day, hour] = data.map(item => item.value);
					// datetime 有日期限制
					if (compareIsEqual([year, month, day, hour], [this.startYear, this.startMonth, this.startDay, this
							.startHour
						]) && this.startMinute) {
						minuteData = minuteData.filter(item => item.value * 1 >= this.startMinute * 1)
					} else if (compareIsEqual([year, month, day, hour], [this.endYear, this.endMonth, this.endDay, this
							.endHour
						]) && this.endMinute) {
						minuteData = minuteData.filter(item => item.value * 1 <= this.endMinute * 1)
					}
				}

				return minuteData;
			},
			/**
			 * 根据起始时间，限定日期
			 */
			formatDay(data, dayData) {
				const [year, month] = data.map(item => item.value);
				if (this.startYear == year && month == this.startMonth && this.startDay) {
					dayData = dayData.filter(item => item.value * 1 >= this.startDay * 1);
				} else if (this.endYear == year && month == this.endMonth && this.endDay) {
					dayData = dayData.filter(item => item.value * 1 <= this.endDay * 1);
				}
				return dayData;
			},
			/**
			 * 根据起始时间，限定月份
			 */
			formatMonth(data) {
				let monthData = this.monthData;

				const [year] = data.map(item => item.value);
				// if(![this.startYear,this.endYear].includes(year)){
				// 	return this.monthData;
				// }
				if (this.startYear == year && this.startMonth) {
					// 起始年
					monthData = this.monthData.filter(item => item.value * 1 >= this.startMonth * 1)
				} else if (this.endYear == year && this.endMonth) {
					// 起始年
					monthData = this.monthData.filter(item => item.value * 1 <= this.endMonth * 1)
				}


				return monthData;
			},
			/**
			 * 计算年、月天数
			 * @param {Object} data
			 */
			handleComputedDay(data) {
				const [year, month, day] = data.map(item => item.value);

				// 可清除状态下，修复报错问题
				if (!year || !month) {
					return;
				}
				let date = new Date(year, month, 0);
				let dayData = new Array(date.getDate()).fill(0).map((val, index) => {
					let value = index + 1;
					if (value < 10) {
						value = '0' + value;
					}
					let item = {
						value,
						label: value + '日'
					}
					if (this.showDay && this.showTime) {
						item.label = value;
					}

					return item;
				})

				return dayData;
			},
			/**
			 * 懒加载，主要处理不同年月、月份的不同天数
			 * @param {Object} info
			 * @param {Object} selected
			 * @param {Object} fn
			 */
			handleLoadColumn(info, selected, fn) {
				// 加载月
				if (this.showYear && this.showMonth && selected.length == 1) {
					// 限定起始时间，开始年没有之前的月份；结束年没有后面的月份

					fn(this.formatMonth(selected));
					return
				}
				// 加载天
				if (this.showYear && this.showDay && selected.length == 2) {
					let dayDate = this.handleComputedDay(selected);
					// 限定起始时间，开始年没有之前的日期；结束年没有后面的日期
					fn(this.formatDay(selected, dayDate));

					return
				}
				// 在加载datetime加载时
				if (this.showYear && this.showTime) {
					// 展示日期、时间
					// 移除掉懒加载层级数据中的children
					switch (selected.length) {
						case 3: {
							fn(this.formatHour(selected));
							break;
						}
						case 4: {
							fn(this.formatMinute(selected));
							break;
						}
						case 5: {
							fn(this.formatSeconds(selected));
							break;
						}
						default:
					}
					return
				}
				// 仅展示时、分、秒时
				if (!this.showYear && this.showTime) {
					switch (selected.length) {
						case 1: {
							fn(this.formatMinute(selected));
							break;
						}
						case 2: {
							fn(this.formatSeconds(selected));
							break;
						}
						default:
					}
				}
			},
			handleInitValue() {
				
				// 默认当前展示
				let [year, month, day, hour, minute, second] = this.currentDate;
				let initValue = this.value;
				// 默认展示当前日期
				if (!this.value) {
					if(month<10){
						month='0'+month;
					}
					if(day<10){
						day = '0'+day;
					}
					initValue = [year, month, day].join('-')+" "+[hour, minute, second].join(':');
				}
				let values = [];

				// 仅展示年、
				if (this.showYear && !this.showMonth) {
					this.displayValue = [{
						value: this.value || year
					}];
					return
				}
				// 仅展示月
				if (!this.showYear && this.showMonth) {
					let value = this.value || month;
					if (this.value * 1 < 10 && this.value.length < 2) {
						value = "0" + value;
					}
					this.displayValue = [{
						value
					}];
					return
				}
				let date = this.value?this.value.split(" "):initValue.split(" ");
				if (this.showDay || this.showMonth) {
					values.push(...date[0].split('-'))

					if (this.showTime) {
						values.push(...date[1].split(':'))
					}
				} else if (this.showTime) {
					let time = date.length>1?date[1]:date[0]
					values.push(...time.split(':'))
				}

				let select = [];
				while (values.length > 0) {
					select.push({
						value: values.shift()
					})
				}

				this.displayValue = select;
			},
			init() {
				// 当前时间
				const [year, month, day, hour, minute, second] = this.currentDate;
				// 指定的范围数据
				// const [start, end] = this.gap;
				if (this.showYear) {
					// 初始化年份数据
					let data = [];
					// 
					let startYear = this.startYear || (year - 15);
					let endYear = this.endYear || (year + 15)
					for (let i = startYear; i <= endYear; i++) {
						data.push(i)
					}
					this.yearDate = data.map(val => {
						let item = {
							value: val,
							label: val + '年',
						}
						if (this.showDay && this.showTime) {
							item.label = val;
						}
						return item
					});
				}
				// 初始月份数据
				this.monthData = new Array(12).fill(0).map((val, index) => {
					let value = index + 1;
					if (value < 10) {
						value = '0' + value
					}
					let item = {
						value,
						label: value + '月'
					}
					// 
					if (this.showDay && this.showTime) {
						item.label = value
					}
					return item;
				})

				// 时间 - 小时
				this.secondsData = new Array(60).fill(0).map((val, index) => {
					let value = index;
					if (value < 10) {
						value = '0' + value
					}
					return {
						value: value,
						label: value
					}
				})
				this.minutesData = this.secondsData.map(item => ({
					...item,
					// children: this.secondsData
				}))
				this.hoursData = new Array(24).fill(0).map((val, index) => {
					let value = index;
					if (value < 10) {
						value = '0' + value
					}
					return {
						value: value,
						label: value,
						// children: this.minutesData
					}
				});
			},

			initPickerData() {
				let data = [];

				if (this.showYear) {
					data = this.yearDate;

				} else if (this.showMonth) {
					// 仅展示月份
					data = this.monthData
				}
				if (this.showTime && !this.showDay) {
					// 仅展示时间
					// 增加时间限定：起始时间、截止时间
					if (this.startHour && this.endHour) {
						data = this.hoursData.filter(item => item.value * 1 >= this.startHour && item.value * 1 <= this
							.endHour)
					} else if (this.startHour) {
						data = this.hoursData.filter(item => item.value * 1 >= this.startHour)
					} else if (this.endHour) {
						data = this.hoursData.filter(item => item.value * 1 <= this.endHour)
					} else {
						data = this.hoursData;
					}
				}
				this.data = data;
			},
			handleFormatValue(data) {
				
				if (this.valueFormat && typeof this.valueFormat == 'function') {
					return this.valueFormat(data)
				}

				let arr = data.map(item => item.value);

				let value = '';

				// 存在年、月、日
				if (this.showDay || (this.showYear && this.showMonth)) {
					value = arr.slice(0, 3).join('-');

					// 存在时间一起
					if (this.showTime) {
						value = value + " " + arr.slice(3).join(':');
					}
					return value;
				}
				// 时间
				if (this.showTime) {
					value = arr.slice(0, 3).join(':');
					return value;
				}

				return arr[0]
			},
			handleConfirm(info, selected) {
				
				let value = this.handleFormatValue(selected)

				this.$emit('ok', value, selected.map(item => item.value))
			}
		},

	}
</script>
<style>
</style>